<template>
  <div class="relative overflow-auto" v-loading="loading" element-loading-text="正在快速处理中...">
    <div class="absolute z-50 bg-white top-0 left-0 right-0">
      <div class="flex gap-3">
        <!-- 刷选语言 -->
        <el-select
        v-model="language"
        placeholder="请选择语言"
        style="width: 80px"
        @change="findAllFiles()"
      >
        <el-option
          v-for="item in languageOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
        <!-- 上传文件按钮 -->
        <el-upload
          :action="`${BaseURL}?lng=zh&type=${activeItem.type}`"
          :headers="{
            authorization: userStore.user.token
          }"
          :show-file-list="false"
          multiple
          @progress="handleUploadProgress"
          @error="handleErrorProgress"
          @success="handleUploadSuccess"
        >
          <el-button type="success">上传文件</el-button>
        </el-upload>
        <!-- 取消选择按钮 -->
        <el-button type="primary" @click="activeData = []">取消选择</el-button>
        <el-button @click="handleFileDeleteClick()" type="danger">删除选中</el-button>
      </div>
      <!-- 展示头部控件 -->
      <ul class="flex gap-3 border-b">
        <template v-for="item of fileTypes" :key="item.type">
          <li
            @click="(activeItem = item), (activeData = [])"
            :class="activeItem.name == item.name && 'text-blue-500 border-b-2 border-blue-400'"
            class="px-3 cursor-pointer select-none py-2"
          >
            {{ item.name }}
          </li>
        </template>
      </ul>
    </div>
    <!-- 显示数据 -->
    <ul class="columns-5 mt-20 overflow-y-auto">
      <template v-for="item of filterData" :key="item.ID">
        <li
          :title="item.filename"
          style="border-color: transparent"
          class="p-2 pb-6 select-none hover:text-red-600 relative mb-1 overflow-hidden border-2 cursor-pointer rounded"
          :class="activeData.indexOf(item) != -1 && 'border-green-400'"
          @click="HandleFileClick(item)"
        >
          <img class="w-full" :src="returnUrl(item.url)" :alt="item.filename" />
          <span class="absolute select-text truncate bottom-0">{{ item.filename }}</span>
        </li>
      </template>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore, useProductFileStore } from '@/stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FindFileService, DeleteFileService } from '@/service'
import { computed } from 'vue'
import { onMounted } from 'vue'
import { languageOptions } from '@/utils'
// 父组件传递过来的数据
const props = defineProps<{
  showMode: string
}>()
// 筛选数据值
const language = ref('zh')
// 选项卡的数据源
const fileTypes: { name: string; type: string }[] = [
  {
    name: '商品展示图片',
    type: 'image'
  },
  {
    name: '商品文件/文档',
    type: 'file'
  },
  {
    name: '说明书',
    type: 'instruction'
  },
  {
    name: '图纸',
    type: 'drawing'
  },
  {
    name: '软件',
    type: 'software'
  }
]
// 返回当前选项卡的所有数据
const filterData = computed(() =>
  fileStore.FileInfos.filter((item) => item.filetype == activeItem.value.type)
)
// 组件双向绑定的数据
const urls = defineModel<string>({ default: null })

// 获取用户的数据
const userStore = useUserStore()
const fileStore = useProductFileStore()
// 上传图片时提示用户在ing中
const loading = ref(false)
// 选择的当前显示Tabs栏数据
const activeItem = ref({
  name: '商品展示图片',
  type: 'image'
})

function returnUrl(url: string) {
  const imageRegex = /\.(jpg|jpeg|png|gif|bmp|webp)$/i;
  if(imageRegex.test(url)){
    return url
  } else {
    return "http://i18nport.dongsongkeji.com.cn/upload/3346c4c3-c2a3-53ad-958a-ce029b95b21e.png"
  }
}
// 选择中活跃的数据
const activeData = ref<any[]>([])
// 上传文件的 Base URL
const BaseURL = import.meta.env.VITE_UPLOAD_FILE_URL
// 2. 上传文件触发的三个函数
// 2.1 处理文件触发完成的函数
function handleUploadSuccess(response: any) {
  ElMessage({
    type: response.code == 0 ? 'success' : 'error',
    message: response.msg
  })
  loading.value = false
  // if (response.code == 0) {
  findAllFiles()
  // }
}
// 2.2 处理文件触发的进度函数
function handleUploadProgress() {
  loading.value = true
}
// 2.3 处理文件触发的错误函数
function handleErrorProgress() {
  loading.value = false
}

function HandleSelectFileClick() {
  const data = activeData.value.map((item) => {
    return {
      filename: item.filename,
      url: item.url,
      type: activeItem.value.type == 'file' ? 'file' : 'image'
    }
  })
  urls.value = JSON.stringify(data)
}

// 3. 删除选中的图片
function handleFileDeleteClick() {
  console.log('=> handleFileDeleteClick', activeData.value)
  ElMessageBox.confirm(
    '删除之后不可恢复，不可查看！如有使用中的文件，请谨慎操作！',
    '确定删除选择的文件吗？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    DeleteFileService(activeData.value, activeItem.value.type).then((res) => {
      findAllFiles()
    })
  })
}
// 1.1 在生命周期的钩子获取所有的数据
function findAllFiles() {
  // 1.1 获取所有的图片数据
  FindFileService(language.value).then((res) => {
    fileStore.FileInfos = res.data
  })
}
// 点击数据的回调函数
function HandleFileClick(item: any) {
  const index = activeData.value.findIndex((itemy: any) => itemy.url == item.url)
  if (index == -1) {
    activeData.value.push(item)
  } else {
    activeData.value.splice(index, 1)
  }
}

onMounted(() => {
  activeItem.value = fileTypes.find((item) => item.type == props.showMode)!
  if (urls.value) {
    const s = JSON.parse(urls.value).map((item: any) => item.url)
    const data: any[] = []
    fileStore.FileInfos.forEach((item) => {
      if (s.includes(item.url)) return data.push(item)
    })
    activeData.value = data
  }
})
defineExpose({
  HandleSelectFileClick
})
</script>
<style></style>
